package com.example.controller;

import com.example.entity.User;
import com.example.entity.vo.Login;
import com.example.repository.UserRepository;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserRepository repository;

    public UserController(UserRepository repository) {
        this.repository = repository;
    }

    @GetMapping
    public List<User> getAll() {
        return repository.findAll();
    }

    @PostMapping("/login")
    public Boolean login(@RequestBody Login login) {
        Optional<User> userOptional = repository.findByUserName(login.getUserName());
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            String dbPwd = user.getPwd();
            String inputPwd = login.getPwd();
            return dbPwd.equals(inputPwd);
        } else {
            System.out.println("用户不存在: " + login.getUserName());
            return false;
        }
    }

    @PostMapping
    public User create(@RequestBody User user){
        return repository.save(user);
    }
    @PutMapping("/{id}")
    public User update(@PathVariable String id, @RequestBody User user) {
        user.setUserId(id);
        return repository.save(user);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable String id) {
        repository.deleteById(id);
    }

    @GetMapping("/test")
    public String testDatabase() {
        return "Database connection is working!";
    }
}
